package com.ddxz.demo.liquibase.configure;

import com.ddxz.demo.liquibase.mapper.TenantMapper;
import com.ddxz.demo.liquibase.service.LiquibaseService;
import org.springframework.boot.context.event.SpringApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;

import java.util.List;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/12/17
 */

public class LiquibaseListener implements ApplicationListener<SpringApplicationEvent>, Ordered {
    /**
     * Handle an application event.
     * 系统启动之后，更新已存在租户的表结构，保证每次都是最新的代码
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(SpringApplicationEvent event) {
        List<String> tenantList = mapper.getAllTenantNames();
        tenantList.forEach(tenant -> service.updateTenant(tenant));
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

    private final LiquibaseService service;

    private final TenantMapper mapper;

    public LiquibaseListener(LiquibaseService service, TenantMapper mapper) {
        this.service = service;
        this.mapper = mapper;
    }
}
